package com.mysteel.member.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mysteel.common.exception.BizCodeEnum;
import com.mysteel.member.exception.CommonException;
import com.mysteel.member.vo.MemberLoginVo;
import com.mysteel.member.vo.SocialUserLoginVo;
import com.mysteel.member.vo.UserRegisterVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysteel.common.utils.PageUtils;
import com.mysteel.common.utils.Query;

import com.mysteel.member.dao.MemberDao;
import com.mysteel.member.entity.MemberEntity;
import com.mysteel.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    private MemberService memberService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void registerUser(UserRegisterVo registerVo) throws CommonException {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        MemberEntity memberEntity = new MemberEntity();
        // 根据手机号校验用户是否已经注册
        MemberEntity mobile = memberService.getOne(new QueryWrapper<MemberEntity>().eq("mobile", registerVo.getPhone()));
        if (mobile != null){
            // 手机号已被注册
            throw new CommonException(BizCodeEnum.PHONE_HAS_BE_TAKEN.getCode(),BizCodeEnum.PHONE_HAS_BE_TAKEN.getMsg());
        }
        MemberEntity username = memberService.getOne(new QueryWrapper<MemberEntity>().eq("username", registerVo.getUsername()));
        if (username != null){
            // 用户名已被占用
            throw new CommonException(BizCodeEnum.USERNAME_HAS_BE_TAKEN.getCode(),BizCodeEnum.USERNAME_HAS_BE_TAKEN.getMsg());
        }
        // 组装数据，密码加密
        memberEntity.setUsername(registerVo.getUsername());
        memberEntity.setNickname(registerVo.getUsername());
        memberEntity.setMobile(registerVo.getPhone());
        memberEntity.setPassword(passwordEncoder.encode(registerVo.getPassword()));
        // 保存用户数据
        this.baseMapper.insert(memberEntity);
    }

    @Override
    public MemberEntity login(MemberLoginVo loginVo) throws CommonException {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        // 查询用户信息
        MemberEntity userInfo = memberService.getOne(new QueryWrapper<MemberEntity>().eq("username", loginVo.getAccount()).or().eq("mobile", loginVo.getAccount()));
        if (userInfo == null){
            throw new CommonException(BizCodeEnum.ACCOUNT_PASSWORD_WRONG.getCode(),BizCodeEnum.ACCOUNT_PASSWORD_WRONG.getMsg());
        }
        // 密码匹配
        boolean matches = passwordEncoder.matches(loginVo.getPassword(), userInfo.getPassword());
        if (matches){
            return userInfo;
        }
        // 用户名或密码错误，登录失败
        throw new CommonException(BizCodeEnum.ACCOUNT_PASSWORD_WRONG.getCode(),BizCodeEnum.ACCOUNT_PASSWORD_WRONG.getMsg());

    }

    @Override
    public MemberEntity socialUserLogin(SocialUserLoginVo loginVo) throws CommonException {
        String uid = loginVo.getUid();
        if (StringUtils.isBlank(uid)){
            throw new CommonException(BizCodeEnum.SOCIAL_UID_IS_BLANK.getCode(),BizCodeEnum.SOCIAL_UID_IS_BLANK.getMsg());
        }
        MemberDao baseMapper = this.baseMapper;
        // 判断当前社交账号是否注册过
        MemberEntity socialUser = baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("uid", uid));
        if (socialUser != null){
            // 用户已注册,更新令牌及过期时间
            MemberEntity memberEntity = new MemberEntity();
            memberEntity.setId(socialUser.getId());
            memberEntity.setAccessToken(loginVo.getAccess_token());
            memberEntity.setExpiresIn(loginVo.getExpires_in());
            baseMapper.updateById(memberEntity);

            socialUser.setAccessToken(loginVo.getAccess_token());
            socialUser.setExpiresIn(loginVo.getExpires_in());
            return socialUser;
        }
        // 未查到就注册
        MemberEntity registerUser = new MemberEntity();
        try {
            // 查询用户社交信息
            Map<String, Object> params = new HashMap<>(2);
            params.put("access_token",loginVo.getAccess_token());
            params.put("uid",loginVo.getUid());
            String result = HttpUtil.get("https://api.weibo.com/2/users/show.json", params);
            JSONObject jsonObject = JSON.parseObject(result);
            String name = jsonObject.getString("name");
            String gender = jsonObject.getString("gender");
            registerUser.setNickname(name);
            registerUser.setUsername(name);
            registerUser.setGender("m".equalsIgnoreCase(gender) ? 1 : 0);
        }catch (Exception e){
            log.error("查询社交账号用户信息失败...");
        }

        // 设置令牌，UID，过期时间
        registerUser.setUid(loginVo.getUid());
        registerUser.setAccessToken(loginVo.getAccess_token());
        registerUser.setExpiresIn(loginVo.getExpires_in());
        baseMapper.insert(registerUser);
        return registerUser;
    }
}